var threeSumClosest = function (nums, target) {
var ans = nums[0] + nums[1] + nums[2];
var len = nums.length;
nums.sort((a, b) => a < b ? -1 : (a > b) ? 1 : 0);
for (var i = 0; i < len - 2; i++) {
var j = i + 1;
var k = len - 1;
while (j < k) {
var sum = nums[i] + nums[j] + nums[k];
if (sum === target) return sum;
if (sum > target) k--;
if (sum < target) j++;
if (Math.abs(target - sum) < Math.abs(target - ans)) {
ans = sum;
}
}
}
return ans;
};
def three_sum_closest(nums, target)
nums.sort!
diff = 2 ** 32
nums.each_with_index do |n, i|
left, right = i + 1, nums.length - 1
while left < right
cur_diff = target - nums[left] - nums[right] - n
return target if cur_diff == 0
diff = cur_diff if cur_diff.abs < diff.abs
cur_diff > 0 ? left += 1 : right -= 1
end
end
target - diff
end